"""
简化版配置管理
Simplified Configuration Management
"""
import os
from typing import Dict, Any, Optional
from dataclasses import dataclass, field


@dataclass
class Settings:
    """应用配置类"""
    # 基础配置
    APP_NAME: str = "Python Backend Simplified"
    VERSION: str = "1.0.0"
    DEBUG: bool = False
    PORT: int = 8001
    HOST: str = "localhost"
    SECRET_KEY: str = "your-secret-key-change-in-production"
    
    # 数据库配置
    DATABASE_URL: str = "sqlite:///./data/cameras.db"
    
    # WVP配置
    WVP_BASE_URL: str = "http://localhost:18080"
    WVP_API_KEY: str = ""
    WVP_USERNAME: str = "admin"
    WVP_PASSWORD: str = "admin"
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOGS_DIR: str = "./logs"
    LOG_FILE: str = "app.log"
    LOG_MAX_SIZE: int = 10 * 1024 * 1024  # 10MB
    LOG_BACKUP_COUNT: int = 5
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    
    # AI配置
    AI_ENABLED: bool = True
    AI_MAX_WORKERS: int = 4
    AI_TIMEOUT: int = 30
    AI_MODEL_PATH: str = "./models"
    
    # 视频处理配置
    VIDEO_FRAME_RATE: int = 3
    VIDEO_TIMEOUT: int = 30
    VIDEO_BUFFER_SIZE: int = 1
    
    # 目录配置
    DATA_DIR: str = "./data"
    UPLOAD_DIR: str = "./uploads"
    
    def __post_init__(self):
        """初始化后处理"""
        # 从环境变量读取配置
        self.load_from_env()
        
        # 确保目录存在
        self.ensure_directories()
    
    def load_from_env(self):
        """从环境变量加载配置"""
        # 基础配置
        self.DEBUG = os.getenv("DEBUG", "false").lower() == "true"
        self.PORT = int(os.getenv("PORT", self.PORT))
        self.HOST = os.getenv("HOST", self.HOST)
        self.SECRET_KEY = os.getenv("SECRET_KEY", self.SECRET_KEY)
        
        # 数据库配置
        self.DATABASE_URL = os.getenv("DATABASE_URL", self.DATABASE_URL)
        
        # WVP配置
        self.WVP_BASE_URL = os.getenv("WVP_BASE_URL", self.WVP_BASE_URL)
        self.WVP_API_KEY = os.getenv("WVP_API_KEY", self.WVP_API_KEY)
        self.WVP_USERNAME = os.getenv("WVP_USERNAME", self.WVP_USERNAME)
        self.WVP_PASSWORD = os.getenv("WVP_PASSWORD", self.WVP_PASSWORD)
        
        # 日志配置
        self.LOG_LEVEL = os.getenv("LOG_LEVEL", self.LOG_LEVEL)
        self.LOGS_DIR = os.getenv("LOGS_DIR", self.LOGS_DIR)
        
        # AI配置
        self.AI_ENABLED = os.getenv("AI_ENABLED", "true").lower() == "true"
        self.AI_MAX_WORKERS = int(os.getenv("AI_MAX_WORKERS", self.AI_MAX_WORKERS))
        self.AI_TIMEOUT = int(os.getenv("AI_TIMEOUT", self.AI_TIMEOUT))
        self.AI_MODEL_PATH = os.getenv("AI_MODEL_PATH", self.AI_MODEL_PATH)
        
        # 视频处理配置
        self.VIDEO_FRAME_RATE = int(os.getenv("VIDEO_FRAME_RATE", self.VIDEO_FRAME_RATE))
        self.VIDEO_TIMEOUT = int(os.getenv("VIDEO_TIMEOUT", self.VIDEO_TIMEOUT))
        
        # 目录配置
        self.DATA_DIR = os.getenv("DATA_DIR", self.DATA_DIR)
        self.UPLOAD_DIR = os.getenv("UPLOAD_DIR", self.UPLOAD_DIR)
    
    def ensure_directories(self):
        """确保必要的目录存在"""
        directories = [
            self.DATA_DIR,
            self.LOGS_DIR,
            self.UPLOAD_DIR,
            self.AI_MODEL_PATH
        ]
        
        for directory in directories:
            os.makedirs(directory, exist_ok=True)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'APP_NAME': self.APP_NAME,
            'VERSION': self.VERSION,
            'DEBUG': self.DEBUG,
            'PORT': self.PORT,
            'HOST': self.HOST,
            'DATABASE_URL': self.DATABASE_URL,
            'WVP_BASE_URL': self.WVP_BASE_URL,
            'LOG_LEVEL': self.LOG_LEVEL,
            'AI_ENABLED': self.AI_ENABLED,
            'AI_MAX_WORKERS': self.AI_MAX_WORKERS,
            'VIDEO_FRAME_RATE': self.VIDEO_FRAME_RATE,
            'DATA_DIR': self.DATA_DIR,
            'LOGS_DIR': self.LOGS_DIR,
            'UPLOAD_DIR': self.UPLOAD_DIR,
            'AI_MODEL_PATH': self.AI_MODEL_PATH
        }


# 全局配置实例
_settings: Optional[Settings] = None


def get_settings() -> Settings:
    """获取配置实例"""
    global _settings
    if _settings is None:
        _settings = Settings()
    return _settings


def reload_settings() -> Settings:
    """重新加载配置"""
    global _settings
    _settings = Settings()
    return _settings


# 便捷访问函数
def get_database_url() -> str:
    """获取数据库URL"""
    return get_settings().DATABASE_URL


def get_wvp_config() -> Dict[str, str]:
    """获取WVP配置"""
    settings = get_settings()
    return {
        'base_url': settings.WVP_BASE_URL,
        'api_key': settings.WVP_API_KEY,
        'username': settings.WVP_USERNAME,
        'password': settings.WVP_PASSWORD
    }


def get_ai_config() -> Dict[str, Any]:
    """获取AI配置"""
    settings = get_settings()
    return {
        'enabled': settings.AI_ENABLED,
        'max_workers': settings.AI_MAX_WORKERS,
        'timeout': settings.AI_TIMEOUT,
        'model_path': settings.AI_MODEL_PATH
    }


def get_video_config() -> Dict[str, Any]:
    """获取视频配置"""
    settings = get_settings()
    return {
        'frame_rate': settings.VIDEO_FRAME_RATE,
        'timeout': settings.VIDEO_TIMEOUT,
        'buffer_size': settings.VIDEO_BUFFER_SIZE
    }


def is_debug_mode() -> bool:
    """是否为调试模式"""
    return get_settings().DEBUG


def get_log_config() -> Dict[str, Any]:
    """获取日志配置"""
    settings = get_settings()
    return {
        'level': settings.LOG_LEVEL,
        'dir': settings.LOGS_DIR,
        'file': settings.LOG_FILE,
        'max_size': settings.LOG_MAX_SIZE,
        'backup_count': settings.LOG_BACKUP_COUNT,
        'format': settings.LOG_FORMAT
    }